package com.servlet.download;
//下载文件案例



import com.servlet.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/servlet01")
public class Servlet01 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String filename = request.getParameter("filename");
        //字节流加载进内存
        //1 获取真实路径字节流关联,加载进内存
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        FileInputStream fis = new FileInputStream(realPath);
        //设置响应头
        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);

        //解决中文文加名问题
        String agent = request.getHeader("user-agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        response.setHeader("content-disposition","attachment;filename="+filename);

        ServletOutputStream sos = response.getOutputStream();
        byte[] bytes = new byte[1024*8];
        int len=0;
        while ((len=fis.read(bytes))!=-1) {
            sos.write(bytes);
        }
        fis.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
